package com.xiaoma.common.extend

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.annotation.Keep
import androidx.annotation.MainThread
import androidx.fragment.app.getContainer
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import androidx.viewbinding.ViewBinding
import com.xiaoma.common.ui.BaseActivity
import com.xiaoma.common.ui.BaseFragment

/**
 * author: liangjingbo
 * date: 2022/6/17
 * describe:
 */
@Keep
fun <VB : ViewBinding> BaseActivity<VB>.bind(inflate: (LayoutInflater) -> VB) = lazy(LazyThreadSafetyMode.NONE) {
    inflate(layoutInflater)
}

@Keep
fun <VB : ViewBinding> BaseFragment<VB>.bind(inflate: (LayoutInflater, ViewGroup?, Boolean) -> VB) = object : Lazy<VB> {

    private var cached: VB? = null

    override val value: VB
        get() = cached ?: inflate(layoutInflater, getContainer(), false).also {
            cached = it
            lifecycle.addObserver(object : LifecycleObserver {
                @MainThread
                @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
                fun onDestroy(owner: LifecycleOwner) {
                    owner.lifecycle.removeObserver(this)
                    onDestroyViewProxy()
                    cached = null
                }
            })
        }


    override fun isInitialized(): Boolean = cached != null

}